
/*
 * @(#)MaintDmsUpdateAlertAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.core.DocumentInvitationBean;
import com.dcivision.alert.core.DocumentInvitationManager;
import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.dao.MtmDocumentRelationshipDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.model.BasePageModel;



/**
  MaintDmsUpdateAlertAction.java
  This class is for maint update alert action
    @author          barbin
    @company         DCIVision Limited
    @creation date   25/11/2006
 */

public class MaintDmsInvitationAction extends com.dcivision.alert.web.MaintUpdateAlertAction {

  public static final String SEPARATOR = ",";

  public MaintDmsInvitationAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return ("com.dcivision.alert.dao.UpdateAlertDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return (null);
  }

  /**
   *  Method execute() - set request attributes and call super method
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     ActionForward         Return the action forward object for struts
   *  @throws     ServletException      Throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
	  MaintDmsInvitationForm actionForm = (MaintDmsInvitationForm) form;
	  Connection conn = this.getConnection(request);
	  SessionContainer sessionContainer = this.getSessionContainer(request);
	  String opMode = actionForm.getOpMode()==null?"":actionForm.getOpMode();
	  String actionType = request.getParameter("actionType");

	  DocumentInvitationManager documentInvitationManager;
	  if(!Utility.isEmpty(actionType)){
		  actionForm.setNavMode(actionType);  
	  }
    if(!Utility.isEmpty(actionForm.getDueDate())){
      String subject = actionForm.getSubject()+"[before("+TextUtility.parseDBDateTime(actionForm.getDueDate())+")]";
      actionForm.setSubject(subject);
    }

    if (!Utility.isEmpty(request.getParameter("isReload")) && "false".equals(request.getParameter("isReload"))){
      request.setAttribute("isReload", (String)request.getParameter("isReload"));
    }
    
	  request.setAttribute("actionType",actionForm.getNavMode());
	  if("S".equals(actionForm.getNavMode())){
          //show invitation history
		  if(opMode.equals("LIST_HISTORY")){
			  String docID = (String)request.getSession().getAttribute("documentID");
			  DmsDocument dmsDocument = null;
			  DmsDocument documentRoot = null;   
			  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
			  dmsDocument = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(docID));
        
        DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
        StringBuffer message = new StringBuffer();

        DmsValidation validation = docValidateManager.validateOperateAction(dmsDocument, false, "V");
        List lstIdMisRight = validation.getLstIdReject();
        List lstIdBeLocked = validation.getLstIdlocked();
        List lstIdBeDeleted = validation.getLstIdDeleted();
        List lstIdBeArchived = validation.getLstIdArchived();
        List lstIdRelationship = validation.getLstIdHaveRelationship();
        if (!lstIdMisRight.isEmpty() ||
            !lstIdBeDeleted.isEmpty() ||
            !lstIdBeArchived.isEmpty()){
          for (int i=0; i<lstIdMisRight.size(); i++) {
            this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
          }
          for (int i=0; i<lstIdBeLocked.size(); i++) {
            this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
          }
          for (int i=0; i<lstIdBeDeleted.size(); i++) {
            this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
          }
          for (int i=0; i<lstIdBeArchived.size(); i++) {
            this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
          }
          return mapping.findForward("V");
        }
        //Add ENd
        
			  documentRoot = docRetrievalManager.getRootFolderByRootID(dmsDocument.getRootID());
			  request.setAttribute("dmsDocument",dmsDocument);
		      request.setAttribute("rootFolder", documentRoot);
			  return mapping.findForward("L");
		  }else if(opMode.equals("V")){// advance opertation
			  return mapping.findForward("V");  
		  }else if("COPY".equals(opMode)){//copy document invitation
			  String docID = actionForm.getDocID();
			  String invitationID = actionForm.getInvitationID();
			  this.getInvitationByUpdatAlertID(invitationID,docID,actionForm,request);
			  return mapping.findForward("V");
		  }else if("INS".equals(opMode)){
			  try{
				  documentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
          

          //Add By Jim Zhou       2007/0110       EIP-1292
          DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
          //MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
          String docID = (String)request.getSession().getAttribute("documentID");
          //Integer documentID = TextUtility.parseIntegerObj(actionForm.getID());
          DmsDocument document = docRetrievalManager.getDocument(Integer.valueOf(docID));
          if(!Utility.isEmpty(document.getEffectiveEndDate()) && !Utility.isEmpty(document.getEffectiveStartDate())){
            String dueDate = actionForm.getDueDate();
            if(!Utility.isEmpty(dueDate)){
              if(document.getEffectiveEndDate().getTime()<TextUtility.parseDBDateTimeToTimeStamp(dueDate).getTime()){
                throw new ApplicationException("errros.dms.invitation.duedate.morethan.effective_day");
              }
              
            }
          }
          DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
          StringBuffer message = new StringBuffer();

          DmsValidation validation = docValidateManager.validateOperateAction(document, false, "V");
          List lstIdMisRight = validation.getLstIdReject();
          List lstIdBeLocked = validation.getLstIdlocked();
          List lstIdBeDeleted = validation.getLstIdDeleted();
          List lstIdBeArchived = validation.getLstIdArchived();
          List lstIdRelationship = validation.getLstIdHaveRelationship();
          if (!lstIdMisRight.isEmpty() ||
              !lstIdBeDeleted.isEmpty() ||
              !lstIdBeArchived.isEmpty()){
            for (int i=0; i<lstIdMisRight.size(); i++) {
              this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
            }
            for (int i=0; i<lstIdBeLocked.size(); i++) {
              this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
            }
            for (int i=0; i<lstIdBeDeleted.size(); i++) {
              this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
            }
            for (int i=0; i<lstIdBeArchived.size(); i++) {
              this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
            }
            return mapping.findForward("V");
          }
          //Add ENd
          
				  documentInvitationManager.createInvitation(actionForm);
			  }catch(ApplicationException appEx){
				  this.rollback(request);
			      handleApplicationException(request, appEx);
			  }
			  catch(Exception e){
          log.error(e, e);
			  }
			  if (isError(request)) {
		        return mapping.findForward("V");
		      } else {
            List responseMessagesList = new ArrayList();
            responseMessagesList.add("dms.label.invitation_send_successfully");
            InvitationMessagePageModel messagePageModel = new InvitationMessagePageModel(responseMessagesList, mapping, request, response);
            request.setAttribute(BasePageModel.PAGE_MODEL_KEY, messagePageModel);
		        return mapping.findForward("R");
		      }
		  }else if("QUICK".equals(opMode)){
			  try{
				  documentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
				  documentInvitationManager.createInvitation(actionForm); 
			  }catch(Exception e){
          log.error(e, e);
			  }
			  String docID = (String)request.getSession().getAttribute("documentID");
			  DmsDocument dmsDocument = null;
			  DmsDocument documentRoot = null;   
			  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
			  dmsDocument = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(docID));
			  documentRoot = docRetrievalManager.getRootFolderByRootID(dmsDocument.getRootID());
			  request.setAttribute("dmsDocument",dmsDocument);
		      request.setAttribute("rootFolder", documentRoot);
			  return mapping.findForward("L");
		  }else if("P".equals(opMode)){
			  String docID = request.getParameter("documentID");
			  request.getSession().setAttribute("documentID",docID);
			  actionForm.setDocID(docID);
			  if(Utility.isEmpty(docID)){
				  docID = (String)request.getSession().getAttribute("documentID");
			  }
			  DmsDocument dmsDocument = null;
			  DmsDocument documentRoot = null;   
			  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
			  dmsDocument = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(docID));
			  documentRoot = docRetrievalManager.getRootFolderByRootID(dmsDocument.getRootID());
			  request.setAttribute("dmsDocument",dmsDocument);
		      request.setAttribute("rootFolder", documentRoot);
		      if (DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())){
		          MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
		          Integer targetDocID = docRelationshipDAO.getTargetDocIDByRelatedDocID(dmsDocument.getID(), dmsDocument.getDocumentType());
		          DmsDocument targetDoc = docRetrievalManager.getDocument(targetDocID);
		          if (targetDoc==null || GlobalConstant.RECORD_STATUS_INACTIVE.equals(targetDoc.getRecordStatus())){
		            this.addError(request, DmsErrorConstant.TARGET_DOCUMENT_NOT_FOUND);
		          }
		          request.setAttribute("targetDoc", targetDoc);
		          docRelationshipDAO=null;
		       }
			  return mapping.findForward("L");
		  }else{
			  String docID = request.getParameter("documentID");
        
        request.getSession().setAttribute("documentID",docID);
        actionForm.setDocID(docID);

        //Add By Jim Zhou       2007/0110       EIP-1292
        DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
        DmsDocument document = docRetrievalManager.getDocument(Integer.valueOf(docID));
        DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
        StringBuffer message = new StringBuffer();

        DmsValidation validation = docValidateManager.validateOperateAction(document, false, "V");
        List lstIdMisRight = validation.getLstIdReject();
        List lstIdBeLocked = validation.getLstIdlocked();
        List lstIdBeDeleted = validation.getLstIdDeleted();
        List lstIdBeArchived = validation.getLstIdArchived();
        List lstIdRelationship = validation.getLstIdHaveRelationship();
        if (!lstIdMisRight.isEmpty() ||
            !lstIdBeDeleted.isEmpty() ||
            !lstIdBeArchived.isEmpty()){
          for (int i=0; i<lstIdMisRight.size(); i++) {
            this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
          }
          for (int i=0; i<lstIdBeLocked.size(); i++) {
            this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
          }
          for (int i=0; i<lstIdBeDeleted.size(); i++) {
            this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
          }
          for (int i=0; i<lstIdBeArchived.size(); i++) {
            this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
          }
          return mapping.findForward("V");
        }
        //Add End
        
			  return mapping.findForward("V");
		  }
	  } else{
		  // transact mutiple document invitation
		  if("INS".equals(opMode)){
			  try{
				  String docIDArray = (String)request.getSession().getAttribute("docIDArray");
				  String[] docIDs = TextUtility.splitString(docIDArray,",");
				  for(int i=0; i<docIDs.length; i++){
					  String id = docIDs[i];
					  actionForm.setDocID(id);
					  documentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
					  documentInvitationManager.createInvitation(actionForm);
				  }
			  }catch(ApplicationException appEx){
				  this.rollback(request);
			      handleApplicationException(request, appEx);
			  }
			  catch(Exception e){
          log.error(e, e);
			  }
			  if (isError(request)) {
		        return mapping.findForward("V");
		      } else {
            List responseMessagesList = new ArrayList();
            responseMessagesList.add("dms.label.invitation_send_successfully");
            InvitationMessagePageModel messagePageModel = new InvitationMessagePageModel(responseMessagesList, mapping, request, response);
            request.setAttribute(BasePageModel.PAGE_MODEL_KEY, messagePageModel);
		        return mapping.findForward("R");
		      }
		  }else{
			  String docIDArray = request.getParameter("documentID"); 
			  request.getSession().setAttribute("docIDArray",docIDArray);
			  return mapping.findForward("V");
		  }
	  }
  }
  
  /*************************
   * function: this method pass inviteID get the invitation record. 
   * and set its value to form. complete the copy document invitation
   * operate.
   * @param inviteID
   * @param docID
   * @param actionForm
   */
  private void getInvitationByUpdatAlertID(String inviteID,String docID,MaintDmsInvitationForm actionForm,HttpServletRequest request){
	  DocumentInvitationManager m_DocumentInvitationManager;
	  DocumentInvitationBean invitationBean;
	  Connection conn = this.getConnection(request);
	  SessionContainer sessionContainer = this.getSessionContainer(request);
	  m_DocumentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
	  try{
		  invitationBean = (DocumentInvitationBean)m_DocumentInvitationManager.getInvitationByUpdateAlertID(inviteID);
		  actionForm.setFormData(invitationBean);
	  }catch(Exception e){
      log.error(e, e);
	  }
  }
  
  /*
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   * 
   * Inner Classes Section.
   * 
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   */
  public class InvitationMessagePageModel extends BasePageModel {
    
    private List ResponseMessagesList = null;
    
    private InvitationMessagePageModel(List responseMessagesList, ActionMapping mapping, HttpServletRequest request, HttpServletResponse response) {
      super("dms.label.invitation_send", mapping, request, response);
      this.ResponseMessagesList = responseMessagesList;
    }

    /**
     * @return the responseMessagesList
     */
    public List getResponseMessagesList() {
      return ResponseMessagesList;
    }
    
  }
}